package com.pll.service;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import com.pll.constant.ConstantField;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * @className: CaptchaService
 * @author: XR_Z
 * @date: 2025/6/8 20:42
 * @Version: 1.0
 * @description: 验证码图片生成
 */
@Service
public class CaptchaService {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    public void createCaptcha(HttpServletResponse response, HttpServletRequest request) throws IOException {

        // 获取或创建 Session（true 表示若不存在则创建）
        HttpSession session = request.getSession(true);
        String sessionId = session.getId();

        // 定义图形验证码的长、宽、验证码字符数、干扰元素个数
        CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(200, 100, 4, 30);
        // 图形验证码写出，可以写出到文件，也可以写出到流
        captcha.write(response.getOutputStream());
        // 关闭流
        response.getOutputStream().close();

        //将验证码的值存到redis中
        redisTemplate.opsForValue().set(ConstantField.MerchantsKey.CAPTCHA_VALUE+sessionId,captcha.getCode());
    }

}
